#include "func.h"

struct func* constrFunc(char name[128], int line)
{
	struct func *ret=malloc(sizeof(struct func));
	
	strcpy(ret->name, name);
	ret->start=line;
	ret->end=-1;
	ret->suivant=NULL;
	ret->reference=malloc(100*sizeof(int));
	ret->nReference=0;

	return ret;
}

struct save_func* constrSaveFunc()
{
	struct save_func *ret=malloc(sizeof(struct save_func));
	ret->size=0;
	ret->tete=ret->queue=NULL;

	return ret;
}

void addParam(struct save_func *s, char name[128], int reference[100], int n)
{
	struct func *select=getFunc(s, name);

	int i;
	for(i=0; i<n; ++i)
		select->reference[i]=reference[i];
	select->nReference=n;
}

void addFunc(struct save_func *s, char name[128], int line)
{	
	struct func *ret=constrFunc(name, line);
	
	if(s->size==0)
	{
		s->tete=s->queue=ret;
		s->size++;
	}
	else
	{
		s->queue->suivant=ret; 
		s->queue=ret;	
		s->size++;
	}
}

struct func* getFunc(struct save_func *s, char name[128])
{
	if(s!=NULL)
	{
		struct func *courant=s->tete;
	
		while(courant!=NULL)
		{
			if(strcmp(name, courant->name)==0) return courant;
			courant=courant->suivant;
		}
	}

	return NULL;
}

void nettoyerSaveFunc(struct save_func *s)
{
	if(s!=NULL && s->size>0)
	{
		struct func *courant=s->tete, *supp;

		while(courant!=NULL)
		{
			supp=courant;
			courant=courant->suivant;
			free(supp->reference);
			free(supp);
			s->size--;
		}
	}
}

void affichageFunc(struct save_func *s)
{
	if(s!=NULL)
	{
		struct func *courant=s->tete;
		char buffer[128];

		printf("\nListe des fonctions:\n\nNombre de fonction=%d;\n", s->size);

		while(courant!=NULL)
		{
			sprintf(buffer, "Nom=%s; Debut=%d; Fin=%d;\n Param=", courant->name, courant->start, courant->end);

			int i;
			for(i=0; i<courant->nReference; ++i)
			sprintf(buffer, "%s %d", buffer, courant->reference[i]);
		
			sprintf(buffer, "%s\n", buffer);
			printf("%s\n", buffer);
			courant=courant->suivant;
		}
	}
}
